package com.liu.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.liu.constants.RedisPrefix;
import com.liu.controller.dto.PasswordDTO;
import com.liu.controller.dto.UserDTO;
import com.liu.entity.Admin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.liu.service.UserService;
import com.liu.entity.User;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lsy
 * @since 2023-01-15
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
@Slf4j
public class UserController {

    /**
     * 用户对象
     */
    private UserService userService;
    @Autowired
    @Qualifier("UserServiceImpl")
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    /**
     * 登录
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    public Map<String, Object> loginUser(@RequestBody UserDTO userDTO, HttpSession session) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        Map<String, Object> result = new HashMap<>();
        log.info("登录的用户名:{} 登录的密码:{}", username, password);
        HashMap<String, Object> map = new HashMap<>();
        map.put("username",username);
        map.put("password",password);
        try {
            User userDB = userService.login(map);
            log.info("登录的用户:{}", userDB.toString());
            result.put("success", true);
            result.put("data", userDB);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("data", e.getMessage());
        }
        return result;
    }

    /**
     * 注册
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody UserDTO userDTO){
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        Map<String, Object> map = new HashMap<>();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            map.put("success",false);
            map.put("message","用户名或密码为空");
            return map;
        }
        User userDB = findUserByName(username);
        if(userDB != null){
            map.put("success",false);
            map.put("message","该用户名已存在");
            return map;
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(userDTO.getNickname());
        userService.addUser(user);
        map.put("success",true);
        map.put("message","注册成功");
        return map;
    }

    /**
     * 人员总数
     * @param username
     * @param address
     * @return
     */
    @GetMapping("/count")
    public int findCount(@RequestParam(defaultValue = "") String username,
                         @RequestParam(defaultValue = "") String address) {
        return userService.selectTotal(username,address);
    }

    /**
     * 查询所有用户
     *
     */
    @GetMapping("/list")
    public List<User> findAllUser(){
        return userService.findAllUser();
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Map<String, Object> findPage(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam(defaultValue = "") String username,
                                        @RequestParam(defaultValue = "") String address){
        pageNum = (pageNum - 1) * pageSize;
        List<User> data = userService.selectPage(pageNum, pageSize, username, address);
        Integer total = userService.selectTotal(username,address);
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     * 添加或更新
     *
     * @param user
     */
    @PostMapping("/editUser")
    public int insert(@RequestBody User user) {
        log.info("当前保存或修改用户信息:{}", user.toString());
        //根据传递过来的参数studentId是否存在来决定进入哪个方法
        if (user.getId() != null && user.getId().toString().length() > 0) {
            System.out.println(user.getId());
            return userService.updateUser(user);
        } else {
            System.out.println(user.getId());
            return userService.addUser(user);
        }
    }

    /**
     * 修改密码
     * @param passwordDTO
     * @return
     */
    @PostMapping("/password")
    public int updatePwd(@RequestBody PasswordDTO passwordDTO){
        return userService.updatePwd(passwordDTO);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/delUser")
    public int deleteUser(Integer id){
        log.info("当前删除用户的id:{}", id);
        return userService.deleteUser(id);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/delBatch")
    public int deleteBatch(@RequestBody List<Integer> ids){
        return userService.deleteByIds(ids);
    }

    /**
     * 导出文件
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //从数据库查询所有数据
        List<User> list = userService.findAllUser();
        //在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
//        writer.addHeaderAlias("id","ID");
        //一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);

        //设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset-utf-8");
        String fileName = URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    /**
     * 导入文件
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Boolean  imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<User> list = reader.readAll(User.class);
        System.out.println(list);
        return userService.saveBatch(list);
    }

    /**
     * 根据id查找
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public User user(Integer id){
        return userService.selectUserById(id);
    }


    /**
     * 根据用户名查找
     * @param username
     * @return
     */
    @PostMapping("/findUserByName")
    public User findUserByName(String username){
        return userService.findUserByName(username);
    }
}

